package org.truenewx.tnxjee.service.reminder.manager;

import java.util.ArrayList;
import java.util.List;

import org.truenewx.tnxjee.service.reminder.model.ReminderDescriptor;
import org.truenewx.tnxjee.service.reminder.model.ReminderType;

public class ReminderManager {

    private static final ThreadLocal<List<ReminderDescriptor>> REMINDERS = ThreadLocal.withInitial(ArrayList::new);

    public static ReminderDescriptor add(ReminderType type, String key, String code, Object... args) {
        ReminderDescriptor reminder = new ReminderDescriptor(type, key, code, args);
        List<ReminderDescriptor> reminders = REMINDERS.get();
        if (key != null) {
            for (int i = 0; i < reminders.size(); i++) {
                if (key.equals(reminders.get(i).getKey())) {
                    reminders.set(i, reminder);
                    return reminder;
                }
            }
        }
        reminders.add(reminder);
        return reminder;
    }

    public static ReminderDescriptor add(ReminderType type, String code, Object... args) {
        return add(type, null, code, args);
    }

    public static ReminderDescriptor add(String key, String code, Object... args) {
        return add(null, key, code, args);
    }

    public static ReminderDescriptor add(String code, Object... args) {
        return add(null, null, code, args);
    }

    public static List<ReminderDescriptor> getAndClear() {
        List<ReminderDescriptor> descriptors = REMINDERS.get();
        ArrayList<ReminderDescriptor> result = new ArrayList<>(descriptors);
        descriptors.clear();
        return result;
    }

}
